<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Credit_model extends CI_Model {

	function __construct(){
        parent::__construct();
    }

	function arrays($key){
    	$data = array(
    		/** 积分类型 */
    		'creditNidType' => array(
				'email'          => '1',
				'realname'       => '2',
				'phone'          => '3',
				'video'          => '4',
				'scene'          => '5',
				'zhengjian'      => '6',
				'invest_success' => '7',
				'borrow_success' => '8',
    			'repayment3_success' => '12',
    			'repayment1_success' => '13',
    			'repayment_success' => '14',
    			'award'			 => '15',
    			'decr'			 => '16',
    			'other_decr'	 => '17',
			),
			/** 积分类型名称 */
			'creditTypeName'=>array(
				'1'  => '邮箱认证',
				'2'  => '实名认证',
				'3'  => '手机认证',
				'4'  => '视频认证',
				'5'  => '现场认证',
				'6'  => '上传证件',
				'7'  => '投标成功',
				'8'  => '借款成功',
				'12' => '提前3天以上还款',
				'13' => '提前1-3天以上还款',
				'14' => '还款成功',
				'15' => '奖励',
				'16' => '兑换扣除',
				'17' => '其他扣除'
			),
			/** 积分类型名称 */
			'creditOpName'=>array(
				'1'  => '增加',
				'2'  => '减少',
			)

    	);


    	if($key && isset($data[$key])){
    		return $data[$key];
    	}else{
    		return array();
    	}
    }

	/**
     * 初始化用户积分
     */
    function init_credit($parms = array()){
		if(isset($parms['user_id']) &&  $parms['user_id'] > 0){
			$this->db->insert('zjy_credit', $parms);
    		return $this->db->affected_rows();
		}else{
			return false;
		}
    }

    /**
     * 获取用户积分
     */
    function get_row($user_id = 0){
    	$user_id = intval($user_id);
		if($user_id < 1){
			return false;
		}
		$key = 'zjy_credit_' . $user_id;
		$this->mycache->delete($key);//@todo
		$row = $this->mycache->get_array($key);
		if($row == false){
			$query = $this->db->get_where('zjy_credit', array('user_id' => $user_id));
			$row = $query->row_array();
			if($row){
				$this->mycache->set_array($key,$row);
			}
		}
		return $row;
    }

    /**
     * 更新用户积分
     */
    function update_credit($parms = array()){
    	if(isset($parms['user_id'])){
			$user_id = $parms['user_id'];
			unset($parms['user_id']);
    		$this->db->where('user_id', $user_id);
			$this->db->update('zjy_credit', $parms);
			$res = $this->db->affected_rows();
	    	if($res > 0){
				$key = 'zjy_credit_'.$user_id;
				$this->mycache->delete($key);
			}
			return $res;
		}else{
			return false;
		}
    }

    /**
     * 添加日志
     */
    function add_log($parms = array()){
    	if(isset($parms['user_id']) &&  $parms['user_id'] > 0){
			$this->db->insert('zjy_credit_log', $parms);
    		return $this->db->affected_rows();
		}else{
			return false;
		}
    }

    /**
     * 增加积分
     * @param $log array(user_id,type_id,op,credit_value,remark,op_user,add_time,addip)
     */
    function incr_credit($log = array()){
    	//$user_id = isset($data['user_id']) ? intval($data['user_id']) : 0;
    	$res = false;
    	if(isset($log['user_id']) && $log['user_id'] > 0){
    		$res = self::add_log($log);
    		if($res){
    			$credit = self::get_row($log['user_id']);
    			if(!$credit){
    				//初始化用户积分
			    	$init = array(
			    		'user_id'       => $log['user_id'],
			    		'credit_value'  => 0,
			    		'no_available'  => 0,
			    		'available'     => 0,
			    		'op_user'       => $log['op_user'],//@todo 操作的管理员
			    		'add_time'      => $log['add_time'],
			    		'addip'         => $log['addip'],
			    		'updatetime'    => $log['add_time'],
			    		'updateip'      => $log['addip'],
			    	);
					if(self::init_credit($init)){
						$credit = $init;
					}
    			}
    			$tmp = array(
    				'user_id' => $log['user_id'],
    				'credit_value' => $log['op'] == 1 ? ($credit['credit_value'] + $log['credit_value']) : ($credit['credit_value'] - $log['credit_value']),
    				'available' => $log['op'] == 1 ? ($credit['available'] + $log['credit_value']) : ($credit['available'] - $log['credit_value']),
    				'op_user' => $log['op_user'],
    				'updatetime' => $log['add_time'],
    				'updateip' => $log['addip'],
    			);
    			$res = self::update_credit($tmp);
    		}
    	}
    	return $res;
    }

	/**
     * 扣除积分
     * @param $log array(user_id,type_id,op,credit_value,remark,op_user,add_time,addip)
     */
    function decr_credit($log = array()){
    	$res = false;
    	if(isset($log['user_id']) && $log['user_id'] > 0){
    		$res = self::add_log($log);
    		if($res){
    			$credit = self::get_row($log['user_id']);
    			$tmp = array(
    				'user_id' => $log['user_id'],
    				'credit_value' => $credit['credit_value'],
    				'available' => $credit['available'] - $log['credit_value'],
    				'op_user' => $log['op_user'],
    				'updatetime' => $log['add_time'],
    				'updateip' => $log['addip'],
    			);
    			$res = self::update_credit($tmp);
    		}
    	}
    	return $res;
    }

    function get_pic($credit){
    	$key = 'zjy_credit_rank';
    	$this->mycache->delete($key);//@todo
    	$list = $this->mycache->get_array($key);
    	if($list == false){
    		$this->db->select('id,point1,point2,pic');
    		$query = $this->db->get('zjy_credit_rank');
    		$list = $query->result_array();
    		$this->mycache->set_array($key, $list, 0);
    	}

    	foreach($list as $v){

    		if($credit >= $v['point1'] && $credit <= $v['point2']){
    			return $v['pic'];
    		}
    	}
    	return false;
    }

	function credit_type(){
    	$key = 'zjy_credit_type';
    	$list = $this->mycache->get_array($key);
    	if($list == false){
    		$query = $this->db->get('zjy_credit_type');
    		$res = $query->result_array();
    		$list = array();
    		foreach($res as $val){
    			$list[$val['id']] = $val;
    		}
    		$this->mycache->set_array($key, $list, 0);
    	}
    	return $list;
    }

	function credit_type_list($per_page=0,$page_size=20){
    		$limit = " limit {$per_page},{$page_size}";
    		$sql = "select * from zjy_credit_type {$limit}";
    		$query = $this->db->query($sql);
    		$list['list'] = $query->result_array();

    		$sql = "select count(*) as count from zjy_credit_type";
			$query = $this->db->query($sql);
			$list['count'] = $query->row()->count;
    		return $list;
    }

	function get_credit_list($parms=array(),$per_page=0,$page_size=20){
    	$tmp = array();
		foreach($parms as $key => $val){
			$tmp[] = "`{$key}` = '{$val}'";
		}
		$select = "*";
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);
		$order = "order by id desc";
		$limit = " limit {$per_page},{$page_size}";
		$sql = "select {$select} from zjy_credit_log {$where} {$order} {$limit}";
		$query = $this->db->query($sql);
		$data['list'] = $query->result_array();
		$sql = "select count(*) as count from zjy_credit_log {$where}";
		$query = $this->db->query($sql);
		$data['count'] = $query->row()->count;
		return $data;

    }

	function get_credit_log_list($parms=array(),$per_page=0,$page_size=20,$limit=false){
    	$tmp = array();
		foreach($parms as $key => $val){
			if($val){
				if($key=='strtime'){
					$credit_start = strtotime($val.' 00:00:00');
					$tmp[] = "l.add_time >= '{$credit_start}'";
				}else if($key=='endtime'){
					$credit_end = strtotime($val.' 23:59:59');
					$tmp[] = "l.add_time <= '{$credit_end}'";
				}else{
					$tmp[] = "l.{$key} = '{$val}'";
				}
			}
		}

		$select = "l.*,u.username";
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);
		$order = "order by l.id desc";
		$sql = "select {$select} from zjy_credit_log as l left join zjy_user as u on l.user_id=u.user_id {$where} {$order}";

		if(isset($limit) && $limit == 'all'){
			$query = $this->db->query($sql);
			$data['list'] = $query->result_array();
			return $data;
		}else{
			$limit = " limit {$per_page},{$page_size}";
			$sql .= $limit;
			$query = $this->db->query($sql);
			$data['list'] = $query->result_array();

			$sql = "select count(*) as count from zjy_credit_log as l {$where}";
			$query = $this->db->query($sql);
			$data['count'] = $query->row()->count;
			return $data;
		}
    }

    function get_credit_list_all($parms=array(),$per_page=0,$page_size=20,$limit=false){
    	$tmp = array();
		foreach($parms as $key => $val){
			if($key=='is_loan' ||  $key=='is_self'){
				if($key=='is_loan'){
					$tmp[] = "u.is_loan = '{$val}'";
				}else if($key=='is_self'){
					$tmp[] = "u.is_self = '{$val}'";
				}
			}else{
				if($val){
					$tmp[] = "c.{$key} = '{$val}'";
				}
			}


		}

		$select = "c.*,u.username";
		$where = '';
		$tmp && $where = " where " . implode(' and ', $tmp);
		$order = "order by id desc";

		$sql = "select {$select} from zjy_credit as c left join zjy_user as u on c.user_id=u.user_id {$where} {$order}";
		if(isset($limit) && $limit == 'all'){
			$query = $this->db->query($sql);
			$data['list'] = $query->result_array();
			return $data;
		}else{
			$limit = " limit {$per_page},{$page_size}";
			$sql .= $limit;
			$query = $this->db->query($sql);
			$data['list'] = $query->result_array();

			$sql = "select sum(available) as total ,count(*) as count from zjy_credit as c left join zjy_user as u on c.user_id=u.user_id {$where}";
			$query = $this->db->query($sql);
			$data['count'] = $query->row()->count;
			$data['total'] = $query->row()->total;
			return $data;
		}
    }

	function get_credit_rank(){
	    $this->db->select('id,point1,point2,pic,name,creidt_rank');
	    $this->db->order_by("creidt_rank", "asc");
	    $query = $this->db->get('zjy_credit_rank');
	    return $query->result_array();
    }

	function get_credit_rank_one($id){
	    $query = $this->db->get_where('zjy_credit_rank', array('id' => $id));
		return $query->row_array();

    }

	function update_credit_rank($id,$parms = array()){
	    $this->db->where('id', $id);
		$this->db->update('zjy_credit_rank', $parms);
		$this->mycache->delete('zjy_credit_rank');
		return $this->db->affected_rows();
	}

	function add_credit_rank($parms){
		$this->mycache->delete('zjy_credit_rank');
		$this->db->insert('zjy_credit_rank', $parms);
    	return $this->db->affected_rows();
	}

	function del_credit_rank($id){
		$r = $this->db->query('DELETE FROM zjy_credit_rank WHERE id='.$id.' LIMIT 1');
		return $this->db->affected_rows();
	}

	function update_credit_rule($id,$parms = array()){
	    $this->db->where('id', $id);
		$this->db->update('zjy_credit_type', $parms);
		$this->mycache->delete('zjy_credit_types');
		return $this->db->affected_rows();
	}

	function add_credit_rule($parms){
		$this->db->insert('zjy_credit_type', $parms);
		$this->mycache->delete('zjy_credit_types');
    	return $this->db->affected_rows();
	}

	function del_credit_rule($id){
		$r = $this->db->query('DELETE FROM zjy_credit_type WHERE id='.$id.' LIMIT 1');
		$this->mycache->delete('zjy_credit_types');
		return $this->db->affected_rows();
	}



	function get_credit_rule($param=array()){
		$query = $this->db->get_where('zjy_credit_type', $param);
		return $query->row_array();
	}

	function get_credit_rule_list_name(){
		$this->db->select('id,name');
		$query = $this->db->get('zjy_credit_type');
		$result = $query->result_array();
		$list = array();
		if($result){
			foreach($result as $v){
				$list[$v['id']] = $v['name'];
			}
		}
		return $list;
	}

    //每日登录签到获得5分
    function give_login_credit($user_id = 0){

        $user_id = intval($user_id);
        if($user_id < 1) {
            return false;
        }

        $this->load->model('User_model');
        $userinfo = $this->User_model->get_by_uid($user_id);

        $time = strtotime(date('Y-m-d',time()).' 00:00:00');
        $last_time = strtotime(date('Y-m-d',$userinfo['sign_time']).' 00:00:00');

        if($time == $last_time) {
            return 2;
        } else {
            $sign_num = $userinfo['sign_num']+1;

            //用来判断是否续签的，暂时不需要
//            $qd_time = strtotime(date('Y-m-d',time()).' 00:00:01');//假定当前签到时间为凌晨
//            $sc_time = strtotime(date('Y-m-d',$userinfo['sign_time']).' 00:00:01');//假定上次签到时间为凌晨

            $credit_info = $this->get_credit_rule(array('nid' => 'login'));
            $jifen = $credit_info['credit_value'];
            $type_id = $credit_info['id'];
            $log = array(
                'user_id' => $user_id,
                'type_id' => $type_id,
                'op' => 1,
                'credit_value' => $jifen,
                'remark' => '登录签到获得'.$jifen.'积分',
                'op_user' => time(),
                'addip' => ''
            );
            $this->incr_credit($log);
            $this->User_model->update(array('sign_time'=>time(),'sign_code'=>$jifen+$userinfo['sign_code'],'sign_num'=>$sign_num),array('user_id'=>$user_id));
            return 1;
        }
    }


}